// 武汉绿地"生活与工作"报名H5



// cmd 0 拉去用户数据
// cmd 1 推送用户填写的数据
// cmd 2 后台账号密码登陆
// cmd 3 获得数据表数据


var path = require('path')
var routerApi = require('../../utils/routeString.js')(__filename, __dirname);
var utils = require('../../utils/index.js')
var validate = utils.validate;
var ip = utils.ip;
var SqlHelper = utils.SqlHelper;
var jwt = require('../../utils/jwt.js')



var pushData = function (req, res) {

    var body = req.body || req.query;
    var sqlHelper = new SqlHelper('checkin_whld1120');

    // 信息完整性检查
    if (!validate.isName(body.name) || !validate.isPhone(body.phone) || !body.pp) {

        return res.send({ code: 0, msg: '请填写正确的电话和姓名' });
    }

    var data = {
        pp: body.pp,
        name: body.name,
        phone: body.phone

    }

    sqlHelper.insert(data, (results) => {
        if (results.affectedRows > 0) {
            return res.send({ code: 1 });
        } else {
            return res.send({ code: 0, msg: "系统错误" });
        }

    })
}


var login = async function (req, res, next) {
    var body = req.body || req.query;

    if (!body.account || !body.password) {
        return res.send({ code: 0, msg: '请输入您的账号和密码' });
    }

    if (body.account === "admin" && body.password === "matrixpassword2017") {
        var jwtData = await jwt.encode2(body.account);
        return res.send({ code: 1, token: jwtData.token });
    } else {
        return res.send({ code: 0, msg: '账号密码错误' });
    }

}

// return {list, count, comments}
var getTableData = async function (req, res) {
    var body = req.body || req.query;

    if (!body.token) {
        return res.send({ code: 0, msg: '账号密码错误' });
    }

    try {
        var userid = await jwt.decode(body.token);
        var sqlHelper = new SqlHelper('checkin_whld1120');
        var result = await sqlHelper.asyncSelect(null, body.offset, body.limit);
        var result2 = await sqlHelper.asyncCount() //results[0].num
        var comments = await sqlHelper.asyncComments();
        return res.send({ code: 1, result: { list: result, count: result2[0].num, comments: comments } });
    } catch (error) {
        return res.send({ code: 0, msg: error.message });
    }

}

var analysisFn = function (req, res, next) {
    var body = req.body || req.query;

    var cmd = parseInt(body.cmd);

    // 命令解析
    if (isNaN(cmd)) {
        return res.send({ code: 0, msg: '无效请求, cmd参数出错' });
    }
 
    switch (cmd) {
        // case 0:
        //     getData(req, res, next);
        //     break;
        case 1:
            pushData(req, res);
            break;
        case 2:
            login(req, res, next);
            break;
        case 3:
            getTableData(req, res);
            break;
        default:
            return res.send({ code: 0, msg: '无效请求, cmd参数出错' });
    }
}

server.post({ path: routerApi, name: routerApi }, analysisFn)